package com.ztjava.core.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;

public class UploadUtil {
	public static String upload(Controller controller,Integer user_id) throws Exception{
		return upload(controller,controller.getPara("directory", "other"),user_id);
	}
	public static String upload(Controller controller,String directory,Integer user_id) throws Exception{
		if(user_id==null){
			user_id = 0;
		}
		HttpServletRequest request = controller.getRequest();
		if ("application/octet-stream".equals(request.getContentType())) {
			return uploadByHtml5(request,directory,user_id);
		}else {
			UploadFile uploadFile = controller.getFile("filedata");
			if(uploadFile == null){
				return null;
			}
			return uploadByNormal(uploadFile,directory,  user_id);
		}
	}
	
	public static String uploadByNormal(UploadFile file,String directory,Integer user_id){
		if(file==null) {
			return null;
		}
		String dir = directory+File.separator+DateUtil.formatDateToStr("yyyyMM", new Date())+File.separator+user_id+File.separator;
		String newfilename = getNum(100000000)+FileUtil.getFileExt(file.getFileName());
		String path =  "/upload/"+dir.replace("\\", "/")+newfilename;
		
		
		File newfile = new File(FileUtil.getWebPath()+File.separator+"upload"+File.separator+dir,newfilename);
		if(!newfile.getParentFile().exists()){
			newfile.getParentFile().mkdirs();
		}
		file.getFile().renameTo(newfile); 
		return path;
	}
	
	public static String uploadByHtml5(HttpServletRequest request,String directory,Integer user_id) throws Exception{
		String sFileName = RequestUtil.getHtml5UploadFilename(request);  
		int i = request.getContentLength();  
		byte buffer[] = new byte[i];  
        int j = 0;  
        while (j < i) { // 获取表单的上传文件  
            int k = request.getInputStream().read(buffer, j, i - j);  
            j += k;  
        }  
        if (buffer.length == 0) { // 文件是否为空  
            return null;
        }  
        
        String dir = directory+File.separator+DateUtil.formatDateToStr("yyyyMM", new Date())+File.separator+user_id+File.separator;
        String newfilename = getNum(100000000)+FileUtil.getFileExt(sFileName);
        String path = "/upload/"+dir.replace("\\", "/")+newfilename;
		
		
        String saveFilePath = FileUtil.getWebPath()+File.separator+"upload"+File.separator+dir;
        File fileDir = new File(saveFilePath); // 构建文件目录以及目录文件  
        if (!fileDir.exists()) {  
            fileDir.mkdirs();  
        }  
        
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFilePath+newfilename, true));  
        out.write(buffer);  
        out.close();  
        return path;
	}
	
	private static long num = 0l;
	private static String date;
	public static synchronized String getNum(int max) {  
        String str = new SimpleDateFormat("ddHHmm").format(new Date());  
        if(date==null||!date.equals(str)){  
            date = str;  
            Random n = new Random();
            num  = n.nextInt(max);  
        }  
        num ++;  
        if(num>max){
        	num = num-max;
        }
        long orderNo = Long.parseLong((date)) * max;  
        orderNo += num;;  
        return orderNo+"";  
    }  
}
